/*
 * @Date: 2023-03-11 23:58:10
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-12-28 09:14:47
 * @Description: 业务相关工具类
 */
import Cookies from 'js-cookie'
import config from '@/config'
const { sysCode, cookieExpires } = config
export const TOKEN_KEY = `${sysCode}_token`
export const SID_TOKEN_KEY = `${sysCode}_sidtoken`
export const USUAL_PERSON_KEY = `${sysCode}_usualPerson`
export const REMENBER_LOGIN_KEY = `${sysCode}_remenberLogin`

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) {
  let o = {
    'M+': this.getMonth() + 1, //月份
    'd+': this.getDate(), //日
    'h+': this.getHours(), //小时
    'm+': this.getMinutes(), //分
    's+': this.getSeconds(), //秒
    'q+': Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds() //毫秒
  }

  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (let k in o)
    if (new RegExp('(' + k + ')').test(fmt)) {
      const oVal = o[k as keyof typeof o]
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? oVal : ('00' + oVal).substr(('' + oVal).length))
    }

  return fmt
}

export const cookiesStorage: Storage = {
  setItem(key, value) {
    return Cookies.set(key, value, { expires: cookieExpires || 1 })
  },
  getItem(key: string): string | null {
    return Cookies.get(key) as string | null
  },
  removeItem(key: string): void {
    Cookies.set(key, '', { expires: -1 })
  },
  clear(): void {},
  key(index: number): any {
    return index
  },
  length: 0
}

export const setToken = (token: string) => {
  Cookies.set(TOKEN_KEY, token, { expires: cookieExpires || 1 })
}

export const getToken = () => {
  const token = Cookies.get(TOKEN_KEY)
  return token ? token : false
}

export const setSidToken = (token: string) => {
  Cookies.set(SID_TOKEN_KEY, token, { expires: cookieExpires || 1 })
}

export const getSidToken = () => {
  const token = Cookies.get(SID_TOKEN_KEY)
  return token ? token : false
}

/**
 *  输入date 返回几天前或者几天后的date
 *  校验date格式是否是日期格式需先在函数外处理掉
 * @param date 输入的日期
 * @param day number 当前日期偏移几天 可为正负
 * @param formatRule 返回后的日期格式
 * @returns {any | Date}
 */
export function dateComputeByDay(date: string, day: number, formatRule = 'yyyy-MM-dd') {
  let newDate = new Date(date)
  newDate.setDate(newDate.getDate() + day)
  newDate = new Date(newDate).Format(formatRule)
  return newDate
}
